﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NVelocity;
using System.IO;
using NVelocity.Context;
using NVelocity.App;
using NVelocity.Runtime;
using Commons.Collections;

namespace weikebuluo.Controllers.Cs.Customer
{
    public class TemplateHelper
    {
        private VelocityEngine velocity = null;
        private IContext context = null;
        public TemplateHelper(string templatePath)
        {
            velocity = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            velocity.Init(props);
            context = new VelocityContext();
        }
        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key">模板变量</param>
        /// <param name="value">模板变量值</param>
        public void Put(string key, object value)
        {
            context.Put(key, value);
        }
        /// <summary>
        /// 生成字符
        /// </summary>
        /// <param name="templatFileName">模板文件名</param>
        public string BuildString(string templateFile)
        {
            //从文件中读取模板
            Template template = velocity.GetTemplate(templateFile);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            return writer.ToString();
        }
        /// <summary>
        /// 实例化Velocity引擎并返回模板
        /// </summary>
        public string WriterTemplate(string template, IContext context = null, int expires = 60)
        {
            if (velocity == null)
                velocity = new VelocityEngine();
            velocity.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocity.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(@"\"));
            if (expires != 0)
            {
                velocity.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true);
                velocity.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)expires);//设置被缓模板
            }
            velocity.Init();
            Template tmp = velocity.GetTemplate(template);
            StringWriter writer = new StringWriter();
            if (context == null)
                context = new VelocityContext();
            tmp.Merge(context, writer);
            return writer.ToString();
        }
    }
}